package com.kotlin.use.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.kotlin.use.bean.User
import com.kotlin.use.repository.RoomRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class RoomViewModel : ViewModel() {

    val userListLiveData = MutableLiveData<List<User>>()

    fun loadUserList() {
        viewModelScope.launch(Dispatchers.IO) {
           val userList = RoomRepository().query()
            userListLiveData.postValue(userList)
        }
    }

    fun insertUser(user: User) {
        viewModelScope.launch(Dispatchers.IO) {
            RoomRepository().insertUser(user)
        }
        loadUserList()
    }

    fun deleteUser(name: String) {
        viewModelScope.launch(Dispatchers.IO) {
            RoomRepository().deleteUser(name)
        }
        loadUserList()
    }

    fun updateUser(name: String, age: Int) {
        viewModelScope.launch(Dispatchers.IO) {
            RoomRepository().updateUser(name, age)
        }
        loadUserList()
    }
}
